package com.xctech.yace.swing.tab;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xctech.yace.main.YaceSendFromDB;
import com.xctech.yace.service.FileService;
import com.xctech.yace.swing.ConfigValue;
import com.xctech.yace.swing.FatherSwing;
import com.xctech.yace.swing.InitFileConfig;
import com.xctech.yace.swing.component.ComboboxToolTipRenderer;
import com.xctech.yace.swing.component.LargeComboBoxUI;
import com.xctech.yace.swing.subTab.MonitorSwing;
import com.xctech.yace.util.FormatUtil;
import com.xctech.yace.util.ReadFiledXML;
import com.xctech.yace.util.SelectUtil;
import org.apache.flink.api.java.tuple.Tuple2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

import static javax.swing.JOptionPane.*;

public class MoniTabSwing extends FatherSwing implements ConfigValue, InitFileConfig {

    public static String title = "模拟";
    public static String line = "------------------------------------------------添加模板-----------------------------------------------------------------------------------------------------------------";
    public static AtomicInteger index = new AtomicInteger(0);

    public static Map<String, String> modelMap = ReadFiledXML.readModelFile("conf/json");

    public static Map<String, Map<String,String>> modelFoldMap = ReadFiledXML.readFileNode("conf/json");

    public static JSplitPane genMoniSplitPanel() {
        //发送画板
        JPanel send = new JPanel();
        //监控画板
        JPanel monitor = new JPanel();

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, send, monitor);
        splitPane.setDividerLocation(1100);

        MonitorSwing.placeComponentsRight(monitor);
        placeComponentsMoniLeft(send);

        return splitPane;
    }

    private static void placeComponentsMoniLeft(JComponent panel) {
        /* 布局部分我们这边不多做介绍
         * 这边设置布局为 null
         */
        panel.setLayout(null);

        Properties properties = productPropties();
        String ipport = properties.getProperty("bootstrap.servers");

        JComboBox topicBox=new JComboBox();    //创建JComboBox
        topicBox.addItem("--自定义主题--");    //向下拉列表中添加一项
        topicMap.entrySet().stream().forEach(topics->{
            topics.getValue().stream().forEach(topic->{
                topicBox.addItem(topic);
            });
        });
        topicBox.setBounds(15,20,sfiledW+50,height);
        topicBox.setToolTipText(ipport);
        panel.add(topicBox);

        JTextField topicText = new JTextField(20);
        topicText.setBounds(15+sfiledW+space+40,20,200,height);
        topicText.setFont(new Font("Courier",Font.BOLD,13));
        topicText.setToolTipText(ipport);
        panel.add(topicText);

        JComboBox fileNodeBox=new JComboBox();    //创建JComboBox
        fileNodeBox.addItem("--选择文件夹--");    //向下拉列表中添加一项
        modelFoldMap.entrySet().stream().forEach(fold->{
            fileNodeBox.addItem(fold.getKey());
        });
        fileNodeBox.setBounds(15,20+height+5,sfiledW+50,height);
        panel.add(fileNodeBox);

        //增加模板
        JComboBox addModelBox=new JComboBox();    //创建JComboBox
        addModelBox.addItem(line);    //向下拉列表中添加一项
        modelMap.entrySet().stream().forEach(model->{
            addModelBox.addItem(model.getKey());
        });
        addModelBox.setBounds(15+sfiledW+space+40,20+height+5,sfiledW+530,height);
        addModelBox.setToolTipText("直接选中即添加到到消息框中...");
        addModelBox.setUI(new LargeComboBoxUI());
        panel.add(addModelBox);

        ComboboxToolTipRenderer renderer = new ComboboxToolTipRenderer();
        addModelBox.setRenderer(renderer);

        //单选框
//        JRadioButton singleButton=new JRadioButton("id",false);
//        singleButton.setBounds(590,20,30,height);
//        singleButton.setToolTipText("");
//        panel.add(singleButton);

        //搜索文本框
        JTextField searchText = new JTextField(20);
        searchText.setBounds(630,20,200,height);
        searchText.setFont(new Font("Courier",Font.BOLD,13));
        searchText.setToolTipText(ipport);
        panel.add(searchText);

        // 搜索按钮
        JButton clearButton = new JButton("搜索");
        clearButton.setBounds(840,20,sfiledW,height);
        clearButton.setToolTipText("搜索");
        panel.add(clearButton);

        // 刷新按钮
        JButton flushButton = new JButton("刷新");
        flushButton.setBounds(840,20+height+5,sfiledW,height);
        flushButton.setToolTipText("刷新");
        panel.add(flushButton);

        // 发送按钮
        JButton sendButton = new JButton("发送");
        sendButton.setBounds(960,20,sfiledW,height*2+5);
        sendButton.setToolTipText(ipport);
        panel.add(sendButton);

        //message按钮
        JTextArea area = new JTextArea();
        JScrollPane scrollArea = new JScrollPane(area);

        scrollArea.setMaximumSize(scrollArea.getPreferredSize());
        scrollArea.setBounds(15,20+height*2+space,1057,870);
        scrollArea.setFont(new Font("Courier",Font.BOLD,12));

        scrollArea.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollArea.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        panel.add(scrollArea);


        area.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_DELETE){
                    System.out.println("清空area界面");
                    area.setText("");
                    addModelBox.setSelectedIndex(0);//归零，下次重新选择
                }
                //组合按键  ctrl+f
                if((e.getKeyCode() == KeyEvent.VK_F) && e.isControlDown()){
                    System.out.println("ctrl+f 暂未实现");
                    //1.显示搜索框
                    //2.获取关键信息
                    //String key = topicText.getText();
                    //3.enter查询
                    //area.select(0,10);
                }
                //组合按键  ctrl+s
                if((e.getKeyCode() == KeyEvent.VK_S) && e.isControlDown()){
//                    System.out.println("ctrl+s");
                    if(addModelBox.getSelectedIndex()!=0){
                        String modelKeyFile = addModelBox.getSelectedItem().toString().trim()+"_new.sql";
                        String body = area.getText();
                        FileService.saveFile(modelKeyFile,body);
                        //清空1
                        fileNodeBox.removeAllItems();
                        fileNodeBox.addItem("--选择文件夹--");    //向下拉列表中添加一项
                        modelFoldMap.entrySet().stream().forEach(fold->{
                            fileNodeBox.addItem(fold.getKey());
                        });
                        //清空2
                        modelMap = ReadFiledXML.readModelFile("conf/json");
                        addModelBox.removeAllItems();
                        addModelBox.addItem(line);    //向下拉列表中添加一项
                        modelMap.entrySet().stream().forEach(model->{
                            addModelBox.addItem(model.getKey());
                        });
                        addModelBox.setRenderer(renderer);
                    }
                }
            }
        });


        addModelBox.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED){
                    if(addModelBox.getSelectedIndex()!=0){
                        String modelKey = addModelBox.getSelectedItem().toString().trim();
                        String[] topics = modelKey.split("#");
                        if(topics.length >= 2){
                            topicText.setText(topics[1]);
                        }
                        String[] msgs = modelMap.get(modelKey).split("#{5,}");
                        for(int i = 0;i < msgs.length;i++){
                            String msg = msgs[i];
                            JSONObject jsonObject = JSONObject.parseObject(msg);
                            area.append(FormatUtil.format(JSONObject.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue))+"\n");
                            area.append("##########################################################"+"\n");
                        }
//                        addModelBox.setSelectedIndex(0);//归零，下次重新选择
                    }
                }
            }
        });

        topicBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                topicText.setText("");//重置
                if(topicBox.getSelectedIndex()!=0){
                    String topic = topicBox.getSelectedItem().toString().trim();
                    topicText.setText(topic);
                }
            }
        });

        //文件夹切换
        fileNodeBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                addModelBox.removeAllItems();
                addModelBox.addItem(line);    //向下拉列表中添加一项
                addModelBox.setRenderer(renderer);

                try{
                    if(fileNodeBox.getSelectedIndex()!=0){
                        String key = fileNodeBox.getSelectedItem().toString().trim();
                        Map<String, String> sqlMap = modelFoldMap.get(key);
                        sqlMap.entrySet().stream().forEach(model->{
                            addModelBox.addItem(model.getKey());
                        });
                    }
                }catch (Exception e1){
                    System.out.println("刷新删除导致fileNodeBox调用为空！忽略该问题");
                }
            }
        });

        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String key = searchText.getText();
                String body = area.getText();
                Tuple2<Integer, Integer> sei = SelectUtil.selectKey(key, body, index.get());
                area.requestFocusInWindow();//todo 重要需要获取焦点
                area.select(sei.f0,sei.f1);
                if(sei.f1 == 0){
                    index.set(0);
                }else {
                    index.set(sei.f1);
                }
                //清空area
                //area.setText("");
            }
        });

        flushButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //清空area
                area.setText("");
                //清空1
                modelFoldMap =  ReadFiledXML.readFileNode("conf/json");
                fileNodeBox.removeAllItems();
                fileNodeBox.addItem("--选择文件夹--");    //向下拉列表中添加一项
                modelFoldMap.entrySet().stream().forEach(fold->{
                    fileNodeBox.addItem(fold.getKey());
                });
                //清空2
                modelMap = ReadFiledXML.readModelFile("conf/json");
                addModelBox.removeAllItems();
                addModelBox.addItem(line);    //向下拉列表中添加一项
                modelMap.entrySet().stream().forEach(model->{
                    addModelBox.addItem(model.getKey());
                });
                addModelBox.setRenderer(renderer);
            }
        });

        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String topic = topicText.getText().trim();
                if("".equals(topic)){
                    System.out.println("主题为空");
                    JOptionPane.showMessageDialog(null,"主题为空","kafkaSend",WARNING_MESSAGE);
                    return;
                }
                String message = area.getText().trim();
                if("".equals(message)){
                    System.out.println("消息为空");
                    JOptionPane.showMessageDialog(null,"消息为空","kafkaSend",WARNING_MESSAGE);
                    return;
                }
                Boolean sendOk = YaceSendFromDB.sendNMsg(topic, message.split("#{5,}"));
                if(sendOk){
                    //JOptionPane.showMessageDialog(null,"发送成功","kafkaSend",INFORMATION_MESSAGE);
                    int isClear = showConfirmDialog(null, "               发送成功\n是否清除发送信息？", "发送成功", YES_NO_OPTION);
                    if(isClear == 0){
                        //清空area
                        area.setText("");
                        addModelBox.setSelectedIndex(0);//归零，下次重新选择
                    }
                    index.set(0);
                }else {
                    JOptionPane.showMessageDialog(null,"发送失败","kafkaSend",ERROR_MESSAGE);
                }

            }
        });

    }

}
